"""
指数历史K线数据演示
展示如何使用历史K线API获取长时间范围的数据
"""
from loguru import logger
from datetime import datetime, timedelta
from exchange.index_candlesticks import (
    IndexCandlesticksManager,
    get_history_candlesticks,
    get_candlesticks_range
)


def demo_basic_history():
    """演示基本的历史K线获取"""
    logger.info("=" * 60)
    logger.info("演示1: 获取最近100天的日K线数据")
    logger.info("=" * 60)
    
    # 使用便捷函数
    candlesticks = get_history_candlesticks(
        inst_id="BTC-USD",
        bar="1D",
        limit=100,
        sandbox=True
    )
    
    logger.info(f"获取到 {len(candlesticks)} 条历史K线")
    
    if candlesticks:
        oldest = candlesticks[-1]
        newest = candlesticks[0]
        
        logger.info(f"\n时间范围:")
        logger.info(f"  最早: {oldest['timestamp']}")
        logger.info(f"  最新: {newest['timestamp']}")
        
        logger.info(f"\n价格范围:")
        prices = [c['close'] for c in candlesticks]
        logger.info(f"  最高: ${max(prices):,.2f}")
        logger.info(f"  最低: ${min(prices):,.2f}")
        logger.info(f"  平均: ${sum(prices)/len(prices):,.2f}")


def demo_long_range():
    """演示获取长时间范围的数据"""
    logger.info("\n" + "=" * 60)
    logger.info("演示2: 获取最近1年的周K线数据")
    logger.info("=" * 60)
    
    manager = IndexCandlesticksManager(sandbox=True)
    
    # 获取最近1年的周K线
    end_time = datetime.now()
    start_time = end_time - timedelta(days=365)
    
    logger.info(f"时间范围: {start_time.strftime('%Y-%m-%d')} 至 {end_time.strftime('%Y-%m-%d')}")
    
    candlesticks = manager.get_candlesticks_range(
        inst_id="BTC-USD",
        bar="1W",
        start_time=start_time,
        end_time=end_time,
        use_history_api=True
    )
    
    logger.info(f"获取到 {len(candlesticks)} 条周K线")
    
    if candlesticks:
        # 计算年度涨跌幅
        first_price = candlesticks[0]['close']
        last_price = candlesticks[-1]['close']
        change = last_price - first_price
        change_pct = (change / first_price * 100) if first_price > 0 else 0
        
        logger.info(f"\n年度表现:")
        logger.info(f"  起始价格: ${first_price:,.2f}")
        logger.info(f"  结束价格: ${last_price:,.2f}")
        logger.info(f"  涨跌金额: ${change:+,.2f}")
        logger.info(f"  涨跌幅度: {change_pct:+.2f}%")


def demo_multiple_indexes_history():
    """演示比较多个指数的历史表现"""
    logger.info("\n" + "=" * 60)
    logger.info("演示3: 比较多个指数的历史表现")
    logger.info("=" * 60)
    
    indexes = ["BTC-USD", "ETH-USD", "SOL-USD"]
    
    logger.info("获取最近90天的日K线数据...")
    
    results = {}
    for inst_id in indexes:
        try:
            candlesticks = get_history_candlesticks(
                inst_id=inst_id,
                bar="1D",
                limit=90,
                sandbox=True
            )
            
            if candlesticks:
                first_price = candlesticks[-1]['close']
                last_price = candlesticks[0]['close']
                change_pct = (last_price - first_price) / first_price * 100
                
                results[inst_id] = {
                    "first_price": first_price,
                    "last_price": last_price,
                    "change_pct": change_pct,
                    "candle_count": len(candlesticks)
                }
        except Exception as e:
            logger.error(f"获取 {inst_id} 失败: {e}")
    
    # 按涨跌幅排序
    sorted_results = sorted(results.items(), key=lambda x: x[1]['change_pct'], reverse=True)
    
    logger.info("\n90天涨跌幅排行:")
    for i, (inst_id, data) in enumerate(sorted_results, 1):
        logger.info(f"{i}. {inst_id:12s}: {data['change_pct']:+7.2f}% "
                   f"(${data['first_price']:,.2f} → ${data['last_price']:,.2f})")


def demo_monthly_analysis():
    """演示月度分析"""
    logger.info("\n" + "=" * 60)
    logger.info("演示4: 月度K线分析")
    logger.info("=" * 60)
    
    # 获取最近12个月的月K线
    candlesticks = get_history_candlesticks(
        inst_id="BTC-USD",
        bar="1M",
        limit=12,
        sandbox=True
    )
    
    logger.info(f"获取到 {len(candlesticks)} 条月K线\n")
    
    if candlesticks:
        logger.info("月度表现:")
        logger.info("-" * 80)
        logger.info(f"{'月份':^20s} {'开盘':>12s} {'收盘':>12s} {'涨跌幅':>10s} {'振幅':>10s}")
        logger.info("-" * 80)
        
        for candle in reversed(candlesticks):
            month = datetime.fromtimestamp(candle['timestamp_ms'] / 1000).strftime('%Y-%m')
            open_price = candle['open']
            close_price = candle['close']
            high_price = candle['high']
            low_price = candle['low']
            
            change_pct = (close_price - open_price) / open_price * 100
            amplitude = (high_price - low_price) / low_price * 100
            
            logger.info(f"{month:^20s} ${open_price:>11,.2f} ${close_price:>11,.2f} "
                       f"{change_pct:>9.2f}% {amplitude:>9.2f}%")


def main():
    """主函数"""
    logger.info("指数历史K线数据演示")
    logger.info("API限速: 10次/2s")
    logger.info("可获取最近几年的历史数据")
    logger.info("")
    
    try:
        demo_basic_history()
        demo_long_range()
        demo_multiple_indexes_history()
        demo_monthly_analysis()
        
        logger.info("\n" + "=" * 60)
        logger.info("演示完成")
        logger.info("=" * 60)
        
    except Exception as e:
        logger.error(f"演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
